<?php

namespace app\mobile\controller;

use think\Controller;

use think\Request;
use think\Session;
use \think\Db;
use api\JSSDK;

use app\api\model\User as UserModel;

use app\mobile\extra\phpqucode;
use app\common\library\wechat\WxPayTwo;
use app\common\library\wechat\WxPay;
use app\common\library\wechat\WeChatPay;
use app\common\library\wechat\WxpayService;

//Session::set('openId', 'oHLxFwTgR1Ma3uBBzxdolJGgnXf0');
class Promotion extends Base2
{
	public function activity(){

		$pid = request()->param('pid');
        if(!$pid){
            return $this->error('参数错误');
        }
        $promotion = Db::name('activity_promotion')->where('id',$pid)->find();
        if(!$promotion){
            return $this->error('推广信息不存在！');
        }

        if ($promotion['channel']=='wechat') {
            $this->wxllogin();
        }

    
        $end_time = strtotime($promotion['end_time']);
        if($end_time<time()){
            return $this->error('推广已结束！');
        }

        Db::name('activity_promotion')->where('id', $pid)->setInc('view');

        $info = Db::name('activity')->where('id',$promotion['aid'])->where('status',1)->find();
        if(!$info){
            return $this->error('活动不存在或已结束！');
        }



        // Db::name('activity')->where('id', $id)->setInc('view');
        $this->assign('promotion',$promotion);
        $this->assign('info',$info);

        $jssdk = new JSSDK(Config('appId'), Config('appSecret'));
        $signPackage = $jssdk->GetSignPackage();
        $this->assign('signPackage',$signPackage);

		return $this->fetch('activity');
	}
    public function statistics(){
        $openId = Session::get('openId');
        $this->user = Db::name('user')->where('open_id',$openId)->find();
        $pid = request()->param('pid');
        $promotion = Db::name('activity_promotion')->where('id',$pid)->find();
        if(!$promotion){
            return "//推广信息不存在！";
        }

        //统计表ID
        $id = request()->param('id');

        $userAgent = $_SERVER['HTTP_USER_AGENT'];

        if (strpos($userAgent, 'Windows') !== false) {
            // 操作系统为Windows
            $visitor_os = "Windows";
        } elseif (strpos($userAgent, 'Mac') !== false) {
            // 操作系统为Mac
            $visitor_os = "Mac";
        } elseif (strpos($userAgent, 'Linux') !== false) {
            // 操作系统为Linux
            $visitor_os = "Linux";
        } elseif (strpos($userAgent, 'Android') !== false) {
            // 操作系统为Android
            $visitor_os = "Android";
        } elseif (strpos($userAgent, 'iOS') !== false) {
            // 操作系统为iOS
            $visitor_os = "iOS";
        } else {
            // 无法判断操作系统
            $visitor_os = "";
        }
        
        if(request()->isPost()){
            $last = Db::name('activity_promotion_statistics')->where('id',$id)->find();
            if(!$last){
                exit;
            }

            Db::name('activity_promotion_statistics')->where('id',$id)->update([
                'pid'=>$pid,
                'aid'=>$promotion['aid'],
                'uid'=>$this->user['user_id'],
                'page_duration'=>time()-$last['visit_time'],
                'page_url'=>request()->param('currentUrl'),
                'referrer_url'=>request()->param('referrer_url'),
                'last_ip'=>request()->ip(),
                'visitor_ip'=>request()->ip(),
                'leave_time'=>time(),
                'user_agent'=>$_SERVER['HTTP_USER_AGENT'],
                'screen'=>request()->param('screen'),
                //'visit_count' => Db::raw('visit_count+1'),
            ]);
            exit;
        }else{
            if(!$id){
                $stat = Db::name('activity_promotion_statistics')->where([
                    'pid'=>$pid,
                    'aid'=>$promotion['aid'],
                    'uid'=>$this->user['user_id'],
                    'sid'=>0
                ])->order('id desc')->find();
                if($stat){
                    $sid = $stat['sid']>0?$stat['sid']:0;
                    Db::name('activity_promotion_statistics')->where('id',$stat['id'])->whereOr('sid',$sid)->update([
                        'last_time' => date('Y-m-d H:i:s'), //最后一次访问时间
                        'visit_count' => Db::raw('visit_count+1'),
                    ]);
                }

                    $id = Db::name('activity_promotion_statistics')->insertGetId([
                        'pid'=>$pid,
                        'sid'=>isset($stat['id'])?$stat['id']:0,
                        'aid'=>$promotion['aid'],
                        'uid'=>$this->user['user_id'],
                        'visit_time'=>time(),
                        'page_duration'=>1,
                        'ip'=>request()->ip(),
                        'leave_time'=>0,
                        'last_time'=>date('Y-m-d H:i:s'),
                        'visitor_ip'=>request()->ip(),
                        'last_ip'=>request()->ip(),
                        'visitor_browser'=>'',
                        'visitor_os'=>$visitor_os,
                        'page_url'=>$_SERVER['HTTP_REFERER'],
                        'referrer_url'=>'',
                        'visit_count'=>1
                    ]);
            }
        }


        $url = "/index.php?s=/mobile/promotion/statistics/pid/{$pid}/id/{$id}";

        $js = <<<JSONCODE
        var id=0;
        // 获取访问来源
        var referrer = document.referrer;
        
        // 获取当前访问页面
        var currentUrl = window.location.href;
        var leaveTime = new Date().getTime();
        
        // 获取进入页面的时间戳
        var enterTime = new Date().getTime();
        function statisticsupdate(){
            // 发送数据到后端
            $.ajax({
                url: '{$url}',
                type: 'POST',
                data: {
                    id:{$id},
                    pid:{$pid},
                    aid:{$promotion['aid']},
                    visit_time:enterTime/1000,
                    screen: window.screen.width +'x'+window.screen.height,
                    referrer: referrer,
                    currentUrl: currentUrl,
                    leaveTime: leaveTime,
                },
                success: function(response) {
                    console.log('数据已发送到后端');

                }
            });
        }
        setInterval(function(){statisticsupdate();}, 2000);
        // 监听页面离开事件，计算停留时间并发送数据到后端
        $(window).on('beforeunload', function() {
          // 获取离开页面的时间戳
          leaveTime = new Date().getTime();
  
          statisticsupdate();

        });
        JSONCODE;
        return $js;
    }


}